import { _decorator, Camera, Component, EventTouch, find, Node, UITransform, Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PlayCtrlUI')
export class PlayCtrlUI extends Component {

    @property(Camera)
    camera: Camera = null;
    @property(Node)
    maskBgNode: Node = null;
    private ctrlNode: Node = null;
    private radius: number = 0;

    ctrlDirect: Vec3 = new Vec3();
    onTouchActionCallback: (tag: string) => void = null;
    private hold: boolean = false;
    protected start(): void {

        // 监听触摸事件
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);

        this.ctrlNode = find('CtrlIcon', this.node);
        this.radius = this.getComponent(UITransform).contentSize.width / 2;
    }

    protected update(dt: number): void {
        if (this.hold) {
            this.onTouchHold();
        }
    }

    private onTouchHold() {
        this.onTouchActionCallback && this.onTouchActionCallback('hold');
    }

    private onTouchStart(touchEvent: EventTouch) {
        this.hold = true;

        touchEvent.getLocation(this.touchPos);
        this.touchPos_3v.set(this.touchPos.x, this.touchPos.y, 0);

        this.camera.screenToWorld(this.touchPos_3v, this.touchPos_3v);
        this.node.getComponent(UITransform).convertToNodeSpaceAR(this.touchPos_3v, this.touchPos_3v)
        // 将 ctrlNode 移动到触摸位置
        this.ctrlNode.setPosition(this.touchPos_3v);
        this.ctrlDirect.set(this.touchPos_3v.x, this.touchPos_3v.y, 0)

        this.onTouchActionCallback('start');
    }

    private onTouchEnd(touchEvent: EventTouch) {
        this.hold = false;
        this.ctrlNode.setPosition(Vec3.ZERO.clone());


        this.onTouchActionCallback('end');
    }

    private touchPos = new Vec2()
    private touchPos_3v = new Vec3()
    private onTouchMove(touchEvent: EventTouch) {
        if (this.hold) {
            touchEvent.getLocation(this.touchPos);
            this.touchPos_3v.set(this.touchPos.x, this.touchPos.y, 0);
            this.camera.screenToWorld(this.touchPos_3v, this.touchPos_3v);
            this.node.getComponent(UITransform).convertToNodeSpaceAR(this.touchPos_3v, this.touchPos_3v)

            this.touchPos_3v.z = 0;
            if (this.touchPos_3v.length() > this.radius) {
                this.touchPos_3v = this.touchPos_3v.normalize().multiplyScalar(this.radius);
            }

            this.ctrlDirect.set(this.touchPos_3v.x, this.touchPos_3v.y, 0)
            // 更新 ctrlNode 位置
            this.ctrlNode.setPosition(this.touchPos_3v);


            this.onTouchActionCallback('move');
        }
    }
}


